import { promises } from 'fs';
import Vue from 'vue';
import { registerMap } from 'echarts';
import Cookies from 'js-cookie';
import crpy from '../../utils/secret'
import commonStore from '@/commonStore'

const session = {
    state: {
        sessionid: '',
        uid: '',
        user: null,
        auths: null,
        menus: null,
        isLogin: false,
        mockUser: null,
        menuItemAuthInfo: null//子菜单权限信息，全局路由切换时传入

    },
    getters: {
        mockUser: state => mockUser,
        getMockUser: state => () => {
            if (state.mockUser) return state.mockUser;
            let localSessionData = JSON.parse(localStorage.getItem('sessiondata'));
            let localMockUser = localSessionData && localSessionData.mockUser;
            state.mockUser = localMockUser;
            return localMockUser;
        },
        user: state => user,
        session_id: state => sessionid,
        uid: state => uid,
        getUser: (state) => () => {
            return JSON.parse(localStorage.getItem('user'));
        },
        getUserType: (state) => () => {
            const user = JSON.parse(localStorage.getItem('user'));
            if (user) {
                return user.type;
            }
            return null;
        },
        getSessionId: (state) => () => {
            return localStorage.getItem('sessionid');
        },
        getProjectId: (state) => (sesssion) => {
            let currentUser = (sesssion && sesssion.user) || JSON.parse(localStorage.getItem('user'));
            if (currentUser) {
                return currentUser.currentManageDptId;
            }
        },
        getManageDptIds: (state) => (sesssion) => {
            let currentUser = (sesssion && sesssion.user) || JSON.parse(localStorage.getItem('user'));
            if (currentUser) {
                return currentUser.manageDptIds;
            }
        },
        getGlobal: (state, getters) => (sesssion) => { // 用户各种全局属性
            const user = getters.getUser();
            const mUser = state.mockUser || getters.getMockUser();
            const cUser = mUser ? mUser : ((sesssion && sesssion.user) || user);
            const projectId = cUser && cUser.currentManageDptId;
            let global = {
                'user': user,
                'mockUser': mUser,
                'currentUser': cUser,
                'projectId': projectId,
                'isUndergraduate': !!((projectId && projectId == 1)),
                'isGraduate': !!((projectId && projectId != 1)),
                'isAdmin': false, // 是否管理员
                'isAcdemicDean': false, // 是否教务员
                'isAnyTeacher': false, // 是否任何教师（包含但不限于导师，教师，留办老师, ...）
                'isAdvisor': false, // 是否导师
                'isTeacher': false, // 是否教师，
                'isStudyAroadOfficeTeacher': false, // 是否留办老师
                'isStudent': false, // 是否学生
            };
            if (cUser) {
                if (cUser.type == 2) { // 学生
                    global.isStudent = true;
                } else {
                    if (cUser.currentRole == '1') { // 管理员 or 教务员
                        if (cUser.innerRoles.includes('1')) { // 管理员
                            global.isAdmin = true;
                        } else if (cUser.innerRoles.includes('2')) { // 教务员
                            global.isAcdemicDean = true;
                        } else {
                            // 当前身份（管理员 or 老师）需切换
                        }
                    } else if (cUser.currentRole == '2') { // 各种老师
                        global.isAnyTeacher = true;
                        if (cUser.innerRoles.includes('3')) { // 导师
                            global.isAdvisor = true;
                        } else if (cUser.innerRoles.includes('4')) { // 教师
                            global.isTeacher = true;
                        } else if (cUser.innerRoles.includes('5')) { // 留办老师
                            global.isStudyAroadOfficeTeacher = true;
                        } else {
                            // 当前身份（管理员 or 老师）需切换
                        }
                    }
                }
            }
            return global;
        },
        getFuncUnderPage: (state) => (url) => {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    const list = state.auths.filter((item) => {
                        return item.urlPath == url;
                    });
                    const funcs = {};
                    if (list != null && list.length > 0) {
                        state.auths.forEach(item => {
                            if (item.parentAuthId == list[0].authId) funcs[item.authCode] = true;
                        });
                    }
                    resolve(funcs);
                }, 1000);
            });
        },
        getLabelByPath: (state) => (url) => {
            let label = {};
            const _auths = state.auths || JSON.parse(localStorage.getItem('sessiondata')).auths;
            for (let i = 0; i < _auths.length; i++) {
                if (_auths[i].urlPath && _auths[i].urlPath.trim() != '') {
                    // 去除urlPath尾部多余斜杠
                    _auths[i].urlPath = _auths[i].urlPath.replace(/\/$/g, '');
                    const reg = new RegExp('^\\' + _auths[i].urlPath + '(/[0-9a-zA-Z]*)*(\\?[0-9a-zA-Z&=]*)?$', 'g');
                    if (reg.test(url)) {
                        label.authNameCh = _auths[i].authNameCh;
                        label.authNameEn = _auths[i].authNameEn;
                    }
                }
            }
            return label;
        }
    },
    mutations: {
        set_session_data(state, data) {
            crpy.setter({
                key: data.aesKey,
                iv: data.aesIv
            })
            
            state.sessionid = data.sessionid;
            state.uid = data.uid;
            state.user = data.user;
            state.isLogin = true;
            // setMenusData(state, data.auths);// 设置菜单
            // 培养计划菜单下 过滤 跨院系选课设置
            let list = data.auths;
            if (data.mockUser && (data.mockUser.currentManageDptId * 1 == 1 || data.mockUser.currentManageDptId * 1 == 4)) {
                list = data.auths.filter((e) => {
                    return e.authId !== 375 && e.authId !== 1375 && e.authId !== 2375;
                });
            } else if (data.user && (data.user.currentManageDptId * 1 == 1 || data.user.currentManageDptId * 1 == 4)) {
                list = data.auths.filter((e) => {
                    return e.authId !== 375 && e.authId !== 1375 && e.authId !== 2375;
                });
            }
            setMenusData(state, list);// 设置菜单

            if (data.mockUser) state.mockUser = data.mockUser;
            else state.mockUser = null;
            setUserInfoToLocal(data);

            commonStore.setGlobalState(state)
        },
        clear_login_info(state) {
            state = {
                sessionid: '',
                uid: '',
                user: null,
                auths: [],
                menus: [],
                isLogin: false
            };
            // 清除localStorage
            _.forEach(['uid', 'userName', 'sessionid', 'isLogin', 'setActiveIndex'], (key) => {
                localStorage.removeItem(key);
            });
        },
        set_menus_data(state, data) {
            setMenusData(state, data);
        },
        set_menu_authInfo(state, data) {
            state.menuItemAuthInfo = data
        }
    }
};

function setMenusData(state, data) {
    state.auths = JSON.parse(JSON.stringify(data));
    const menuList = filterMenus(data).sort(sortMenus);
    state.menus = Vue.prototype.$utils.listToTree('authId', 'parentAuthId', menuList);
}

function filterMenus(list) {
    return list.filter((item, index, array) => {
        return item.type == 1;
    });
}

function sortMenus(item1, item2) {
    return item1.orderNo - item2.orderNo;
}

function setUserInfoToLocal(data) {
    localStorage.setItem('uid', data.uid);
    localStorage.setItem('userName', data.user.name);
    localStorage.setItem('sessionid', data.sessionid);
    localStorage.setItem('user', JSON.stringify(data.user));
    localStorage.setItem('isLogin', true);
    // Cookies.set("sessionid", data.sessionid);
    // if (data.mockUser) localStorage.setItem('isLogin', JSON.stringify(data.mockUser));
}
export default session;
